package day15;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public
class ClientThread extends Thread {
    Socket client;
    volatile boolean flag = true;

    public
    ClientThread(Socket client) {
        this.client = client;
    }
    // 添加停止线程的方法


    public
    void run() {
        try (BufferedReader be = new BufferedReader(new InputStreamReader(client.getInputStream()))) {
            while (flag) {
                String msg = be.readLine();
                if (msg == null || msg.equals("exit")) {  // 添加对exit消息的判断
                    flag = false;  // 设置标志位
                    System.out.println("退出聊天");
                    break;
                }
                if (msg != null && !msg.equals("")) System.out.println(msg);
            }
            //什么时候关闭线程？
        } catch (Exception e) {

        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
